<template>
  <div class="discuss-container">
    <!-- 顶部操作栏 -->
    <div class="discuss-header">
      <div class="header-left">
        <h2>社区讨论</h2>
        <div class="filter-section">
          <el-radio-group v-model="sortType" size="large" @change="handleSortChange">
            <el-radio-button :label="1">
              <el-icon><Star /></el-icon> 热门
            </el-radio-button>
            <el-radio-button :label="2">
              <el-icon><Timer /></el-icon> 最新
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="goToAddDiscuss" v-if="userStore.isAuthenticated">
          <el-icon><Plus /></el-icon> 发布讨论
        </el-button>
        <el-button @click="goToMyDiscuss" v-if="userStore.isAuthenticated">
          <el-icon><User /></el-icon> 我的讨论
        </el-button>
      </div>
    </div>

    <!-- 讨论列表 -->
    <div class="discuss-list" v-loading="loading">
      <el-empty v-if="discussList.length === 0" description="暂无讨论"></el-empty>
      
      <div v-else class="discuss-grid">
        <div v-for="item in discussList" 
             :key="item.did" 
             class="discuss-item"
             @click="goToDetail(item.did)">
          <div class="discuss-item-header">
            <h3 class="discuss-title">{{ item.title }}</h3>
            <div class="discuss-meta">
              <div class="author-info">
                <el-avatar :size="24">{{ item.username?.charAt(0).toUpperCase() }}</el-avatar>
                <span class="author-name">{{ item.username }}</span>
              </div>
              <span class="publish-time">{{ formatTime(item.createtime) }}</span>
            </div>
          </div>
          
          <div class="discuss-content">{{ truncateContent(item.content) }}</div>
          
          <div class="discuss-footer">
            <div class="discuss-tags" v-if="item.tags && item.tags.length > 0">
              <el-tag v-for="tag in item.tags" 
                      :key="tag" 
                      size="small" 
                      effect="plain">{{ tag }}</el-tag>
            </div>
            <div class="discuss-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ item.readcount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><ChatLineSquare /></el-icon>
                {{ item.commentcount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon>
                {{ item.supportcount || 0 }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Star, Timer, Plus, User, View, ChatLineSquare } from '@element-plus/icons-vue';
import { getDiscussList } from '../../services/discuss';
import { useUserStore } from '../../stores/user';

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const discussList = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const sortType = ref(1); // 1-热门，2-最新

// 加载讨论列表
const loadDiscussList = async () => {
  loading.value = true;
  try {
    const res = await getDiscussList({
      page: currentPage.value,
      type: sortType.value
    });
    discussList.value = res.data.records || [];
    total.value = res.data.total || 0;
  } catch (error: any) {
    ElMessage.error(error.message || '加载讨论列表失败');
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 24小时内
  if (diff < 24 * 60 * 60 * 1000) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 48小时内
  if (diff < 48 * 60 * 60 * 1000) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 其他
  return date.toLocaleDateString('zh-CN');
};

// 截断内容
const truncateContent = (content: string) => {
  if (!content) return '';
  return content.length > 100 ? content.substring(0, 100) + '...' : content;
};

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadDiscussList();
};

// 处理排序方式变化
const handleSortChange = () => {
  currentPage.value = 1;
  loadDiscussList();
};

// 跳转到发布讨论页面
const goToAddDiscuss = () => {
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  router.push('/discuss/add');
};

// 跳转到我的讨论页面
const goToMyDiscuss = () => {
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  router.push('/discuss/my');
};

// 跳转到讨论详情页面
const goToDetail = (did: number) => {
  router.push(`/discuss/${did}`);
};

// 初始化
onMounted(() => {
  loadDiscussList();
});
</script>

<style scoped>
.discuss-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.discuss-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h2 {
  margin: 0;
  font-size: 24px;
  color: var(--el-text-color-primary);
}

.filter-section {
  display: flex;
  gap: 15px;
}

.discuss-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.discuss-item {
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color-lighter);
}

.discuss-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: var(--el-color-primary-light-5);
}

.discuss-item-header {
  margin-bottom: 15px;
}

.discuss-title {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
  line-height: 1.4;
}

.discuss-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.author-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.discuss-content {
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  min-height: 44px;
}

.discuss-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.discuss-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.discuss-stats {
  display: flex;
  gap: 15px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .discuss-container {
    padding: 15px;
  }

  .discuss-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .header-right {
    display: flex;
    gap: 10px;
  }

  .header-right .el-button {
    flex: 1;
  }

  .discuss-grid {
    grid-template-columns: 1fr;
  }
}
</style> 